import os
import sys
import argparse
import tkinter as tk
from tkinter import filedialog
from p1 import compare_images

def select_image_via_gui(prompt="选择图像"):
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename(title=prompt, filetypes=[("Image files", "*.png;*.jpg;*.jpeg")])
    return file_path

def parse_arguments():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='图像差异检测工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python run_comparison.py --img1 compare_1.png --img2 compare_2.png
  python run_comparison.py --img1 image1.jpg --img2 image2.jpg --output my_result.png
  python run_comparison.py --img1 pic1.png --img2 pic2.png --reference expected.png --no-show
        """
    )

    parser.add_argument('--img1', required=False, default='', help='第一张图片路径')
    parser.add_argument('--img2', required=False, default='', help='第二张图片路径')
    parser.add_argument('--reference', default='result.png', help='参考结果图片路径 (默认: result.png)')
    parser.add_argument('--output', default='generated_difference_result.png', help='输出结果图片路径 (默认: generated_difference_result.png)')
    parser.add_argument('--lang', default='en', choices=['en', 'ch'], help='OCR识别语言 (默认: en)')
    parser.add_argument('--no-show', action='store_true', help='不显示结果窗口')

    return parser.parse_args()

def main():
    args = parse_arguments()

    img1_path = args.img1
    img2_path = args.img2
    result_path = args.reference
    output_path = args.output
    show_result = not args.no_show

    # 如果未指定图片路径，使用交互式方式选择
    if not img1_path:
        img1_path = select_image_via_gui("请选择第一张图片")
    if not img2_path:
        img2_path = select_image_via_gui("请选择第二张图片")

    if not img1_path or not os.path.exists(img1_path):
        print(f"错误: 找不到第一张图片 '{img1_path}'")
        return False

    if not img2_path or not os.path.exists(img2_path):
        print(f"错误: 找不到第二张图片 '{img2_path}'")
        return False

    print(f"输入图片1: {img1_path}")
    print(f"输入图片2: {img2_path}")
    print(f"输出结果: {output_path}")

    if result_path and isinstance(result_path, str) and os.path.exists(result_path):
        print(f"参考结果: {result_path}")
    else:
        print("未提供有效的参考结果图片")
        result_path = None

    print("\n开始图像差异检测...")

    try:
        differences, result_img = compare_images(
            img1_path=img1_path,
            img2_path=img2_path,
            result_path=result_path,
            output_path=output_path,
            show_result=show_result,
            lang=args.lang
        )

        print(f"\n检测完成！共发现 {len(differences)} 个差异")

        if differences:
            print("\n差异详情:")
            for i, (diff_key, diff_info) in enumerate(differences.items(), 1):
                print(f"{i}. {diff_key}")
                print(f"   类型: {diff_info['type']}")
                if diff_info['img1_bbox']:
                    print(f"   图片1位置: {diff_info['img1_bbox']}")
                if diff_info['img2_bbox']:
                    print(f"   图片2位置: {diff_info['img2_bbox']}")
                print()
        else:
            print("\n未发现任何差异")

        print(f"结果已保存到: {output_path}")
        return True

    except Exception as e:
        print(f"\n错误: 图像处理过程中发生异常")
        print(f"详细信息: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = main()
    print("\n程序结束")
